﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;

namespace Extensions
{
    public static class GridViewExtensions
    {
        public static void Init(this GridView gridview, BindingSource bs, bool initialized = false)
        {
            try
            {
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                gridview.ViewCaption = gridview.Name;

                gridview.GridControl.DataSource = null;
                gridview.GridControl.DataSource = bs;
                gridview.PopulateColumns();

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridview.Columns)
                    if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }

                gridview.OptionsView.EnableAppearanceEvenRow = false;
                gridview.OptionsView.EnableAppearanceOddRow = false;

                gridview.OptionsView.ShowViewCaption = true;
                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                
                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }

            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }

            gridview.Appearance.EvenRow.BackColor = (UserLookAndFeel.Default.SkinName == "Office 2007 Black" ? System.Drawing.Color.WhiteSmoke : System.Drawing.Color.FromArgb(250, 245, 245));
        }

        public static void Init(this GridView gridview, DataTable bs, bool initialized = false)
        {
            try
            {
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                gridview.ViewCaption = gridview.Name;

                gridview.GridControl.DataSource = null;
                gridview.GridControl.DataSource = bs;
                gridview.PopulateColumns();

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridview.Columns)
                    if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }

                gridview.OptionsView.EnableAppearanceEvenRow = false;
                gridview.OptionsView.EnableAppearanceOddRow = false;

                gridview.OptionsView.ShowViewCaption = true;
                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;

                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }

            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }

            gridview.Appearance.EvenRow.BackColor = (UserLookAndFeel.Default.SkinName == "Office 2007 Black" ? System.Drawing.Color.WhiteSmoke : System.Drawing.Color.FromArgb(250, 245, 245));
        }

        public static void AddSummary(this GridView gridView, params string[] columnNames)
        {
            gridView.OptionsView.ShowFooter = true;
            foreach (GridColumn col in gridView.Columns)
                if (col.Visible == true)
                {
                    col.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
                    col.SummaryItem.DisplayFormat = "{0:#,##0} records";
                    break;
                }

            foreach (string columnName in columnNames)
            {
                GridColumn gc = gridView.Columns[columnName];

                gc.SummaryItem.FieldName = columnName;
                gc.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gc.SummaryItem.DisplayFormat = "{0:#,##0.#}";
            }
        }

        public static void SetVisibleIndex(this GridView gridView, params string[] orderedColumnNames)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.Visible = false;

            int index = 0;
            foreach (string col in orderedColumnNames)
            {
                GridColumn gc = gridView.Columns[col];
                //gc.Visible = true;
                gc.VisibleIndex = index++;
            }
        }

        public static void SetCaptions(this GridView gridView, params string[] pairs)
        {
            string problematicCols = string.Empty;
            foreach (string pair in pairs)
            {
                try
                {
                    string[] vals = pair.Split(':');
                    string colName = vals[0].Trim();
                    string caption = vals[1].Trim();
                    gridView.Columns[colName].Caption = caption;
                }
                catch
                {
                    problematicCols += pair + ",";
                }
            }
             
        }

        public static void EndEditing(this GridView gridView)
        {
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();
        }

        public static void MakeColumnsReadOnly(this GridView gridView, params string[] columnNames)
        {
            foreach (string columnName in columnNames)
                gridView.Columns[columnName].OptionsColumn.AllowEdit = false;
        }

        public static void MakeReadOnly(this GridView gridView, params string[] ExceptTheseColumns)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.OptionsColumn.AllowEdit = ExceptTheseColumns.Any(gc.FieldName.Contains);

            //gridView.OptionsBehavior.Editable = false;
        }

        public static void MakeEditable(this GridView gridView, params string[] ExceptTheseColumns)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.OptionsColumn.AllowEdit = !ExceptTheseColumns.Any(gc.FieldName.Contains);

            //gridView.OptionsBehavior.Editable = true;
        }

        public static void MakeColumnInvisible(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;
            if (columnNames.Length == 0)
            {
                foreach (GridColumn gc in gridView.Columns)
                    gc.Visible = false;
            }
            else
            {
                foreach (string columnName in columnNames)
                {
                    try
                    {
                        gridView.Columns[columnName].Visible = false;
                    }
                    catch
                    {
                        problematicCols += columnName + ",";
                    }
                }
            }
        }

        public static void FormatAsNumber(this GridView gridView, int decimalPoints, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    string format = "#,###.";
                    for (int i = 0; i < decimalPoints; i++)
                        format += "0";

                    if (format.EndsWith("."))
                        format = format.Substring(0, format.Length - 1);
                    col.DisplayFormat.FormatString = format + ";-" + format + "; ";

                    //col.DisplayFormat.FormatString = "{0:n2}";

                    col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;

                    //col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    //col.DisplayFormat.FormatString = "#,###";
                    //col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;

                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                //ApplicationException aex = new ApplicationException("Sütun sayısal formatlamada hata! Bulunmayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                
            }

        }
    }
}